import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import s from './style.module.css';
import cn from 'classnames';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import Label from '../../../components/Label';
import Helper from '../../../components/Helper';
import Table from '@knownsec/react-component/dist/Table';
import Dialog from '@knownsec/react-component/dist/Dialog';
import Left from './left';
import Right from './right';
import fetchFer from 'API/fetch';
import { withRouter } from 'react-router';
import SvgIcon from './icon';
import Icon from '@knownsec/react-component/dist/Icon';
import Loading from '@knownsec/react-component/dist/Loading';
import Button from '@knownsec/react-component/dist/Button';
import Message from '@knownsec/react-component/dist/Message';

import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer';
import EmptyData from '../../../components/empty/EmptyData';
import { datetime } from '../../../../common/formatter';
import DownOnce from '../../../components/DownOnce';
import CopyBoard from '../../../components/CopyBoard';
import Tooltip from '@kuiper-components/tooltip';

function Detail({
	match: {
		params: { id },
	},
	location,
}) {
	const [visible, setVisible] = useState(false);
	const [title, setTitle] = useState('');
	const [v6No, setV6No] = useState(0);
	const [info, setInfo] = useState({});
	const [v6Data, setV6Data] = useState([]);
	const [basics, setBasics] = useState([]);
	const [showTCv6, setShowTCv6] = useState(false);
	const [diffT, setDiffT] = useState({ t1: '', t2: '' });
	const [excellent, setExcellent] = useState([]);
	const [loading, setLoading] = useState(true);

	const getData = async () => {
		setLoading(true);
		const res = await fetchFer(`/api/v2/repodatas/ipv6?task_session_id=${id}`, {
			method: 'GET',
		}).catch(error => {
			console.log('[ 获取详情❌ ]-35', error);
			return {};
		});
		setInfo(res.results || {});
		initBasics(res.results?.event_detail, res.results);
		setLoading(false);
	};
	const initBasics = (detail, info_) => {
		if (!detail || !info_) {
			return;
		}
		setV6No(detail?.http_get_sequence?.ipv6_result);
		const data1 = [
			{
				monitor: 'DNS记录',
				ipv4: detail.dns?.address,
				ipv6: detail.dns?.address_v6,
				score: (detail.dns?.ipv6_score || 0) + '分',
			},
			{
				monitor: '首页可达',
				ipv4: detail.http_get_page?.is_ipv4_support,
				ipv6: detail.http_get_page?.is_ipv6_support,
				score: (detail.http_get_page?.ipv6_score || 0) + '分',
			},
			{
				monitor: '域名授权体系',
				ipv4: detail.ipv6_dns_check?.is_all_support_ipv4,
				ipv6: detail.ipv6_dns_check?.is_all_support_ipv6,
				score: (detail.ipv6_dns_check?.ipv6_score || 0) + '分',
			},
			{
				monitor: '域名解析时延',
				ipv4: detail.dns?.time,
				ipv6: detail.dns?.time_v6,
				score: '不计分',
			},
			{
				monitor: 'TCP时延',
				ipv4: detail.tcp_time?.time,
				ipv6: detail.tcp_time?.time_v6,
				score: '不计分',
			},
			{
				monitor: '首页响应时延',
				ipv4: detail.http_get_full_time?.time_v4,
				ipv6: detail.http_get_full_time?.time_v6,
				score: '不计分',
			},
		];
		const http_rate =
			info_.http_rate > 0 ? `成功率${info_.http_rate.toFixed(2)}%` : '- -';
		const ipv6Page = type => {
			const support = detail?.ipv6_website_support_check;
			return support
				? `支持率${(support[type].intra_normal_urls_proportion * 100).toFixed(
						2
				  )}%`
				: '未检测';
		};
		const data2 = [
			{
				monitor: '网站二级链接IPv6支持率',
				score:
					(detail.ipv6_website_support_check?.secondary_urls_statistics
						?.ipv6_score || 0) + '分',
				result: ipv6Page('secondary_urls_statistics'),
				type: 2,
			},
			{
				monitor: '网站三级链接IPv6支持率',
				score:
					(detail.ipv6_website_support_check?.tertiary_urls_statistics
						?.ipv6_score || 0) + '分',
				result: ipv6Page('tertiary_urls_statistics'),
				type: 3,
			},
			{
				monitor: '网站首页IPv6访问成功率',
				score: (detail.http_get_sequence?.ipv6_score || 0) + '分',
				result: `成功率${(
					detail?.http_get_sequence?.ipv6_success_proportion * 100
				).toFixed(2)}%`,
			},
			{
				monitor: '网站首页内容IPv6和IPv4的一致性',
				score: (detail.http_content_check?.ipv6_score || 0) + '分',
				result: `内容一致性${(
					detail.http_content_check?.similarity * 100
				).toFixed(2)}%`,
				text: detail.http_content_check?.text,
				text_v6: detail.http_content_check?.text_v6,
			},
			{
				monitor: '网站首页布局IPv6和IPv4的一致性',
				score: '不计分',
				result: `布局一致性${(
					detail.http_structure_check?.similarity * 100
				).toFixed(2)}%`,
				text: detail.http_structure_check?.text,
				text_v6: detail.http_structure_check?.text_v6,
			},
			{ monitor: '网站IPv6访问的稳定性', score: '不计分', result: http_rate },
		];
		setV6Data(detail.ipv6_dns_check?.ns);
		setBasics(data1);
		setExcellent(data2);
	};
	useEffect(() => {
		!info.task && getData();
	}, []);
	const renderDemo = ({ type, e, row }) => {
		if (row?.monitor === 'DNS记录') {
			if (e?.length > 0) {
				return e.map(item => {
					return (
						<span className={s.cSpan} key={item}>
							<SvgIcon active={5} />
							<span className={s.cSpan1}>
								{type === '4' ? 'A' : 'AAAA'}记录：
								{item ? <CopyBoard text={item} maxWidth="200px" /> : '不支持'}
							</span>
						</span>
					);
				});
			} else {
				return (
					<span className={s.cSpan} key={e}>
						<SvgIcon active={6} />
						<span className={s.cSpan1}>
							{type === '4' ? 'A' : 'AAAA'}记录：不支持
						</span>
					</span>
				);
			}
		} else if (row?.monitor === '首页可达') {
			return (
				<span className={s.cSpan}>
					<SvgIcon active={e ? 5 : 6} />
					<span className={s.cSpan1}>{type === '4' ? 'IPv4' : 'IPv6'}</span>
				</span>
			);
		} else if (row?.monitor === '域名授权体系') {
			return (
				<span className={s.cSpan}>
					<SvgIcon active={e ? 5 : 6} />
					<span className={s.cSpan1}>
						{e ? '支持' : '不支持'}
						{type === '4' ? 'IPv4' : 'IPv6'}授权体系
					</span>
					{type === '6' && (
						<span
							className={s.cSpanA}
							onClick={() => {
								setShowTCv6(true);
							}}
						>
							详情
						</span>
					)}
				</span>
			);
		} else {
			return isNaN(e) ? '- -' : e + 'ms';
		}
	};
	const columns = [
		{
			title: '检测项',
			key: 'monitor',
			dataIndex: 'monitor',
			className: s.w_100,
			render(cur, item) {
				return (
					<p className={s.txtHp}>
						<span>{cur}</span>
						{cur === '首页可达' && (
							<Helper
								className={s.ml10}
								placement="top"
								overlay={
									'连续 10 次 HTTP/HTTPs 访问中，访问成功占比不低于80%。'
								}
							/>
						)}
					</p>
				);
			},
		},
		{
			title: 'IPv4环境下',
			key: 'ipv4',
			dataIndex: 'ipv4',
			render(e, row) {
				return renderDemo({ row, type: '4', e });
			},
		},
		{
			title: 'IPv6环境下',
			key: 'ipv6',
			dataIndex: 'ipv6',
			render(e, row) {
				return renderDemo({ row, type: '6', e });
			},
		},
		{
			title: '评分',
			key: 'score',
			dataIndex: 'score',
			className: 'w100',
			render(e, row) {
				return <p className={cn(e === '不计分' && s.disabled)}>{e}</p>;
			},
		},
	];
	const helpObj = {
		网站二级链接IPv6支持率:
			'网站二级链接IPv6访问可达链接数占总二级链接数的百分比（不计算外链）。',
		网站三级链接IPv6支持率:
			'网站三级链接IPv6访问可达链接数占总三级链接数的百分比（不计算外链）。',
		网站首页IPv6访问成功率:
			'连续 10 次 HTTP/HTTPs 访问中，访问成功的占比。每次访问之间的时间间隔不大于 5 分钟。',
		网站首页内容IPv6和IPv4的一致性:
			' 通过 IPv6 /IPv4互联网 HTTP/HTTPs 访问网站首页，对文字、图片和视频等关键资源进行记录。在两次访问中所获得内容或者资源一致性对比。',
		网站首页布局IPv6和IPv4的一致性:
			'通过 IPv6/IPv4互联网 HTTP/HTTPs 访问网站首页成功后，呈现在用户浏览器或者客户端上的页面布局一致性进行对比。',
		网站IPv6访问的稳定性:
			'通过获取最近一天内网站http任务的平均可用率计算网站IPv6访问稳定性。',
	};
	const columns1 = [
		{
			title: '检测项',
			key: 'monitor',
			dataIndex: 'monitor',
			render(cur, item) {
				return (
					<p className={s.txtHp}>
						<span>{cur}</span>
						<Helper className={s.ml10} placement="top" overlay={helpObj[cur]} />
					</p>
				);
			},
		},
		{
			title: '检测结果',
			key: 'result',
			dataIndex: 'result',
			render(cur, item) {
				return item?.monitor === '网站IPv6访问的稳定性' ? (
					<Tooltip
						overlay={'请前往可用性监测模块添加HTTP任务（不添加源站IP）'}
						placement={'top'}
					>
						<span>{cur}</span>
					</Tooltip>
				) : (
					<span>{cur}</span>
				);
			},
		},
		{
			title: '评分',
			key: 'score',
			dataIndex: 'score',
			render(e, row) {
				return <p className={cn(e === '不计分' && s.disabled)}>{e}</p>;
			},
		},
		{
			title: '操作',
			key: 'oper',
			dataIndex: 'oper',
			render(cur, item) {
				const isNull = item?.result === '- -';
				return (
					<span
						className={cn(s.oper, isNull && s.isNull)}
						onClick={() => {
							if (isNull) return false;
							if (item?.monitor.includes('链接IPv6支持率')) {
								window.location.href = `/#/job-manage/ipv6-monitor/linkDetail/${id}/${item.type}`;
							} else if (item?.monitor !== '网站IPv6访问的稳定性') {
								setTitle(item.monitor);
								setVisible(true);
								setDiffT({ t1: item.text, t2: item.text_v6 });
							} else {
								window.location.href = `/#/job-manage/aviliable-task?filter=%7B"page":1,"limit":10,"target":"${info.task.target}"%7D`;
							}
						}}
					>
						{isNull ? '- -' : '查看详情'}
					</span>
				);
			},
		},
	];
	const columns2 = [
		{
			title: '访问时间',
			key: 'request_at',
			dataIndex: 'request_at',
			render(e) {
				return datetime(e);
			},
		},
		{
			title: '访问状态',
			key: 'status',
			dataIndex: 'status',
			render(cur, item) {
				const num = Math.floor(cur);
				let isOk = 1;
				if (num === 0 || num === 405 || num === 501) {
					isOk = 0;
				}
				return (
					<div className={s.statusBox}>
						<SvgIcon active={isOk ? 5 : 6} />
						{cur > 0 && <span className={cn(s.cSpan1)}>{cur}</span>}
						<span className={cn(s.cSpan1)}>
							{isOk ? '请求成功' : '无法访问'}
						</span>
					</div>
				);
			},
		},
	];
	const columnsV6 = [
		{
			title: 'NS记录',
			key: 'domain',
			dataIndex: 'domain',
		},
		{
			title: 'IPv6地址',
			key: 'address',
			dataIndex: 'address',
			render(cur, item) {
				console.log('[ cur ]-341', cur);
				return cur.length > 0
					? cur.map(item => {
							return (
								<span className={s.cSpan} key={item}>
									<CopyBoard text={item} maxWidth="200px" />
								</span>
							);
					  })
					: '- -';
			},
		},
	];
	const [timer, setTimer] = useState(false)
	const downWord = (record) => {
		if (timer) return;
		setTimer(true);
		const text = `[${record.note}]ScanVIPv6合规检测报告.docx`
		return fetch(`/api/v2/report/one_task/download?task_id=${record._id}`)
			.then(res => {
				if (res.ok) {
					return res.blob();
				}
			})
			.then(blob => {
				const url = (window.webkitURL || window.URL).createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = text;
				a.click();
				setTimer(false);
			})
			.catch(() => {
				Message.show({
					type: 'error',
					message: `导出${text}`,
					placement: 'top',
					style: { width: '25rem' },
				});
				setTimer(false);
			});
	};
	return (
		<div className={s.content}>
			<Breadcrumb className={s.bread}>
				<Item key="job-manage" disabled>
					任务管理
				</Item>
				<Item key="ipv6-monitor">IPv6合规检测</Item>
				<Item>检测结果</Item>
			</Breadcrumb>
			<Loading show={loading} label={''} />
			<div className={cn(s.df, s.aic, s.pt20, 'pr')}>
				<Button disabled={!info?.task?.oid} className={cn('pa r0 df aic', s.downloadPlain)} style={{ top: '-24px' }} onClick={() => downWord({
						_id: info?.task?.oid,
						note: info?.task?.name,
						target: info?.task?.target,
					})}>
					<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
							<g id="控件" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
									<g id="Web安全任务详情表头" transform="translate(-1052.000000, -33.000000)" fill-rule="nonzero">
											<g id="编组-3" transform="translate(1032.000000, 25.000000)">
													<g id="下载" transform="translate(20.000000, 8.000000)">
															<rect id="矩形" fill="#000000" opacity="0" x="0" y="0" width="20" height="20"></rect>
															<path d="M16.3636364,17.9545454 L3.63636363,17.9545454 C2.75772881,17.9545454 2.04545455,17.2422712 2.04545455,16.3636364 L2.04545455,14.5454546 C2.04545455,14.1688968 2.35071495,13.8636364 2.72727273,13.8636364 C3.10383052,13.8636364 3.40909092,14.1688968 3.40909092,14.5454546 L3.40909092,16.3636364 C3.40909093,16.4891556 3.51084438,16.5909091 3.63636363,16.5909091 L16.3636364,16.5909091 C16.4891556,16.5909091 16.5909091,16.4891556 16.5909091,16.3636364 L16.5909091,14.5454546 C16.5909091,14.1688968 16.8961695,13.8636364 17.2727273,13.8636364 C17.6492851,13.8636364 17.9545454,14.1688968 17.9545454,14.5454546 L17.9545454,16.3636364 C17.9545454,17.2422712 17.2422712,17.9545454 16.3636364,17.9545454 L16.3636364,17.9545454 Z M10,12.5090909 C9.81758439,12.5090909 9.64276921,12.4360263 9.51463893,12.3061877 C9.38650865,12.176349 9.31574961,12.0005812 9.31818182,11.8181818 L9.31818182,2.72727273 C9.31818182,2.35071495 9.62344222,2.04545455 10,2.04545455 C10.3765578,2.04545455 10.6818182,2.35071495 10.6818182,2.72727273 L10.6818182,11.8181818 C10.6842504,12.0005812 10.6134913,12.176349 10.4853611,12.3061877 C10.3572308,12.4360263 10.1824156,12.5090909 10,12.5090909 L10,12.5090909 Z M10,13.6772727 C9.81933074,13.6766185 9.64620538,13.6047552 9.51818182,13.4772727 L4.97272727,8.93181818 C4.84392179,8.80457551 4.77142679,8.63105676 4.77142679,8.45 C4.77142679,8.26894324 4.84392179,8.09542449 4.97272727,7.96818182 C5.23994534,7.70479205 5.66914556,7.70479205 5.93636363,7.96818182 L10.4818182,12.5136364 C10.6106237,12.640879 10.6831187,12.8143978 10.6831187,12.9954546 C10.6831187,13.1765113 10.6106237,13.3500301 10.4818182,13.4772727 C10.3537946,13.6047552 10.1806693,13.6766185 10,13.6772727 Z M10,13.6772727 C9.81933074,13.6766185 9.64620538,13.6047552 9.51818182,13.4772727 C9.38937634,13.3500301 9.31688134,13.1765113 9.31688134,12.9954546 C9.31688134,12.8143978 9.38937634,12.640879 9.51818182,12.5136364 L14.0636364,7.96818182 C14.3308544,7.70479205 14.7600547,7.70479205 15.0272727,7.96818182 C15.1560782,8.09542449 15.2285732,8.26894324 15.2285732,8.45 C15.2285732,8.63105676 15.1560782,8.80457551 15.0272727,8.93181818 L10.4818182,13.4772727 C10.3537946,13.6047552 10.1806693,13.6766185 10,13.6772727 L10,13.6772727 Z" id="形状" fill="#0B6FD6"></path>
													</g>
											</g>
									</g>
							</g>
					</svg>
					下载报告
				</Button>
				{/* <div className={s.downBox}>
					<SvgIcon active={info?.task?.oid ? 7 : 8}></SvgIcon>
					<DownOnce
						className={info?.task?.oid ? s.linkBtn : s.linkBtn2}
						record={{
							_id: info?.task?.oid,
							note: info?.task?.name,
							target: info?.task?.target,
						}}
						fileName={`[${info?.task?.name}]ScanVIPv6合规检测报告.docx`}
					/>
				</div> */}
				<div className={cn(s.left)}>
					<Left info={info} />
				</div>
				<div className={cn(s.right)}>
					<Right info={info} />
				</div>
			</div>
			<div className={s.cont}>
				<Label className={s.labelOverview}>
					<span>基础项</span>
				</Label>
				<div>
					<Table columns={columns} data={basics} />
				</div>
				<div className={s.pt20}>
					<Label className={s.labelOverview}>
						<span>评优项</span>
					</Label>
					<div>
						<Table columns={columns1} data={excellent} />
					</div>
				</div>
				<Dialog
					className={cn(title === '网站首页IPv6访问成功率' ? s.w700 : s.w1000)}
					title={title}
					visible={visible}
					onhide={() => setVisible(false)}
					cancelText=""
					confirmText="关闭"
				>
					<div className={s.p20}>
						<div className={s.titleBox}>
							<p className={s.titleBoxP}>
								任务名称：
								<Tooltip overlay={info.task?.name} placement={'top'}>
									<span>{info.task?.name}</span>
								</Tooltip>
							</p>
							<p className={s.titleBoxP}>
								检测地址：
								<Tooltip overlay={info.task?.target} placement={'top'}>
									<span>{info.task?.target}</span>
								</Tooltip>
							</p>
						</div>
						{title === '网站首页IPv6访问成功率' && (
							<div className={s.tableBox}>
								<Table
									columns={columns2}
									data={v6No}
									empty={<EmptyData type={'img'} className={s.nobor} />}
								/>
							</div>
						)}
						{(title === '网站首页内容IPv6和IPv4的一致性' ||
							title === '网站首页布局IPv6和IPv4的一致性') && (
							// 源码取证
							<>
								<div className={s.diffTitle}>
									<p>通过IPv6互联网 HTTP/HTTPs 访问</p>
									<p>通过IPv4互联网 HTTP/HTTPs 访问</p>
								</div>
								<div className={s.diffBox} key={title}>
									{!diffT.t2 && !diffT.t1 ? (
										<EmptyData type={'img'} className={s.nobor} />
									) : (
										<ReactDiffViewer
											styles={{
												line: { 'word-break': ' break-all' },
											}}
											oldValue={diffT.t2}
											newValue={diffT.t1}
											compareMethod={DiffMethod.WORDS}
											splitView={true}
											showDiffOnly={false}
										/>
									)}
								</div>
							</>
						)}
					</div>
				</Dialog>
				<Dialog
					className={s.w700}
					visible={showTCv6}
					onhide={() => setShowTCv6(false)}
					header={
						<div className={s.dialogHeader}>
							<span className={s.dialogTitle}>
								IPv6授权体系详情
								<Helper
									className={s.ml10}
									placement="top"
									overlay={
										'支持IPv6授权体系：在DNS解析过程的整个网元链条里面，所有的DNS服务器和网络都需支持IPv6。'
									}
								/>
							</span>
							<Icon
								type="cancel"
								onClick={() => {
									setShowTCv6(false);
								}}
								className={cn(s.closeDialogBtn)}
							/>
						</div>
					}
					cancelText=""
					confirmText="确认"
				>
					<div className={s.p20}>
						<div className={s.tableBox}>
							<Table
								columns={columnsV6}
								data={v6Data}
								empty={<EmptyData type={'img'} className={s.nobor} />}
							/>
						</div>
					</div>
				</Dialog>
			</div>
		</div>
	);
}
Detail.propTypes = {
	location: PropTypes.any,
	match: PropTypes.shape({
		params: PropTypes.shape({
			id: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(Detail);
